package mspbots.qbd.data.online.balancesheet;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.qbd.common.ResultMsg;
import mspbots.qbd.data.BaseReceiver;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.time.Duration;

/**
 * @author Jay.Yang
 */

@Log4j2
@Component
@RequiredArgsConstructor
public class OnlineBalanceSheetReceiver extends BaseReceiver {

    private final OnlineBalanceSheetRepository balanceSheetRepository;

    @RabbitListener(queues = "quick-books-online.balance.sheet.sync")
    public void processStandard(ResultMsg resultMsg) {
        OnlineBalanceSheet data = OnlineBalanceSheet.builder()
                .tenantId(resultMsg.getTenantId())
                .timePeriod(resultMsg.getEntity().get("timePeriod").textValue())
                .value(resultMsg.getEntity())
                .syncTime(resultMsg.getSyncDate())
                .build();
        this.balanceSheetRepository.findByTenantIdAndTimePeriod(data.getTenantId(), data.getTimePeriod())
                .map(oldData -> {
                    data.setId(oldData.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.balanceSheetRepository::save).block(Duration.ofSeconds(10));
    }
}
